package cn.memorynine.consumer.service;

import cn.hutool.core.bean.BeanUtil;
import cn.memorynine.common.tool.CommonTool;
import cn.memorynine.consumer.mapper.PersonalCenterMapper;
import cn.memorynine.consumer.model.personal.activity.ActivityList;
import cn.memorynine.consumer.model.personal.activity.ActivityListParam;
import cn.memorynine.consumer.model.personal.activity.ActivityListResult;
import cn.memorynine.consumer.model.personal.address.*;
import cn.memorynine.consumer.model.personal.cart.CartItemListParam;
import cn.memorynine.consumer.model.personal.cart.CartItemListResult;
import cn.memorynine.consumer.model.personal.cart.CartItemQuantityParam;
import cn.memorynine.consumer.model.personal.cart.DelCartItemParam;
import cn.memorynine.consumer.model.personal.donation.DonationList;
import cn.memorynine.consumer.model.personal.donation.DonationListParam;
import cn.memorynine.consumer.model.personal.donation.DonationListResult;
import cn.memorynine.consumer.model.personal.forum.*;
import cn.memorynine.consumer.model.personal.order.*;
import cn.memorynine.dao.entity.*;
import cn.memorynine.dao.mapper.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.memorynine.common.model.ResponseWrapper;
import cn.memorynine.consumer.model.personal.center.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* 个人中心
* @author 代码生成器
*/
@Slf4j
@Service
public class PersonalCenterService {

    @Autowired
    private ConsumerMapper consumerMapper;

    @Autowired
    private PersonalCenterMapper personalCenterMapper;

    @Autowired
    private ShopCartCommodityRelationMapper shopCartCommodityRelationMapper;

    @Autowired
    private ShopAddressMapper shopAddressMapper;

    @Autowired
    private ShopOrderMapper shopOrderMapper;

    @Autowired
    private ShopOrderItemMapper shopOrderItemMapper;

    @Autowired
    private ShopOrderStateMapper shopOrderStateMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityStateMapper activityStateMapper;

    @Autowired
    private DonationMapper donationMapper;

    @Autowired
    private ForumMapper forumMapper;

    @Autowired
    private ForumPostMapper forumPostMapper;

    @Autowired
    private ForumPostReplyMapper forumPostReplyMapper;
    /**
     * 个人信息部分
     */
    /**
     * 1.获取个人信息
     * @return
     */
    public ResponseWrapper personalInfo(PersonalInfoParam param){
        PersonalInfoResult personalInfoResult = new PersonalInfoResult();
        Consumer consumer = consumerMapper.selectList(
                Wrappers.<Consumer>lambdaQuery()
                        .eq(Consumer::getAid, param.getTokenConsumerAid())
        ).get(0);
        personalInfoResult.setCustomerName(consumer.getName());
        personalInfoResult.setId(consumer.getId());
        personalInfoResult.setCustomerEmail(consumer.getEmail());
        personalInfoResult.setCustomerPhone(consumer.getPhone());
        personalInfoResult.setSex(consumer.getSex());

        //最后一步，返回结果
        return ResponseWrapper.markSuccess(personalInfoResult);
    }

    /**
     * 2.修改个人信息
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper savePersonalInfo(SavePersonalInfoParam param){
        Consumer consumer = new Consumer();
        consumer.setAid(param.getTokenConsumerAid());
        consumer.setName(param.getCustomerName());
        consumer.setSex(param.getSex());
        consumer.setId(param.getId());
        consumer.setEmail(param.getCustomerEmail());
        consumer.setPhone(param.getCustomerPhone());
        consumerMapper.updateById(consumer);

        //最后一步，返回结果
        return ResponseWrapper.markSuccess();
    }

    /**
     * 3.修改密码
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper saveLoginKey(SaveLoginKeyParam param){
        Consumer consumer = new Consumer();
        consumer.setAid(param.getTokenConsumerAid());
        consumer.setLoginKey(param.getLoginKey());
        consumerMapper.updateById(consumer);
        return ResponseWrapper.markSuccess();
    }

    /**
     * 购物车部分
     */
    /**
     * 1.查看购物车内商品列表
     * @return
     */
    public ResponseWrapper cartItemList(CartItemListParam param){
        List<CartItemListResult> cartItemListResult;
        List<Map<String,Object>> cartItemList = personalCenterMapper.cartItemList(param.getTokenConsumerAid());
        cartItemListResult = CommonTool.mapListToBeanList(cartItemList,CartItemListResult.class);

        //最后一步，返回结果
        return ResponseWrapper.markSuccess(cartItemListResult);
    }

    /**
     * 2.删除购物车项
     * @return
     */
    public ResponseWrapper delCartItem(DelCartItemParam param){
        shopCartCommodityRelationMapper.deleteById(param.getAid());
        //最后一步，返回结果
        return ResponseWrapper.markSuccess();
    }
    /**
     * 3.修改商品数量
     * @return
     */
    public ResponseWrapper cartItemQuantity(CartItemQuantityParam param){
        ShopCartCommodityRelation shopCartCommodityRelation = new ShopCartCommodityRelation();
        BeanUtil.copyProperties(param,shopCartCommodityRelation);
        shopCartCommodityRelationMapper.updateById(shopCartCommodityRelation);
        //最后一步，返回结果
        return ResponseWrapper.markSuccess();
    }

    /**
     * 地址管理部分
     */
    /**
     * 1.获取当前用户的所有地址列表
     */
    public ResponseWrapper addressList(AddressListParam param){
        List<AddressListResult> addressListResults = new ArrayList<>();
        List<ShopAddress> shopAddresses = shopAddressMapper.selectList(
                Wrappers.<ShopAddress>lambdaQuery()
                        .eq(ShopAddress::getConsumerAid, param.getTokenConsumerAid())
                        .eq(ShopAddress::getIsDelete,0)
        );
        shopAddresses.forEach(address->{
            AddressListResult addressListResult = new AddressListResult();
            BeanUtil.copyProperties(address,addressListResult);
            addressListResults.add(addressListResult);
        });
        return ResponseWrapper.markSuccess(addressListResults);
    }
    /**
     * 2.新增/修改地址--获取地址详情
     */
    public ResponseWrapper addressInfo(AddressInfoParam param){
        AddressListResult addressListResult = new AddressListResult();
        List<ShopAddress> shopAddresses = shopAddressMapper.selectList(
                Wrappers.<ShopAddress>lambdaQuery()
                        .eq(ShopAddress::getAid, param.getAid())
        );

        if (!shopAddresses.isEmpty()){
            ShopAddress shopAddress = shopAddresses.get(0);
            BeanUtil.copyProperties(shopAddress,addressListResult);
        }

        return ResponseWrapper.markSuccess(addressListResult);
    }
    /**
     * 3.新增/修改地址
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper saveAddress(SaveAddressParam param){
        ShopAddress shopAddress = new ShopAddress();
        shopAddress.setConsumerAid(param.getTokenConsumerAid());
        shopAddress.setIsDelete(false);
        BeanUtil.copyProperties(param,shopAddress);
        //如果当前地址是默认地址，则将该用户其他地址全部设置为非默认地址
        ShopAddress temp = new ShopAddress();
        temp.setIsDefault(false);
        if (shopAddress.getIsDefault()){
            shopAddressMapper.update(
                    temp,
                    Wrappers.<ShopAddress>lambdaQuery()
                            .eq(ShopAddress::getConsumerAid,param.getTokenConsumerAid())
            );
            shopAddress.setIsDefault(true);
        }

        if (param.getAid().equals(-1)){
            //新增
            shopAddress.setAid(null);
            shopAddressMapper.insert(shopAddress);
        } else {
            //修改
            shopAddressMapper.updateById(shopAddress);
        }

        return ResponseWrapper.markSuccess();
    }
    /**
     * 4.删除地址
     */
    public ResponseWrapper delAddress(DelAddressParam param){
        ShopAddress shopAddress = new ShopAddress();
        shopAddress.setAid(param.getAid());
        shopAddress.setIsDelete(true);
        shopAddressMapper.updateById(shopAddress);
        return ResponseWrapper.markSuccess();
    }

    /**
     * 5.设置默认地址
     */
    public ResponseWrapper defaultAddress(DefaultAddressParam param){
        ShopAddress shopAddress = new ShopAddress();
        shopAddress.setConsumerAid(param.getTokenConsumerAid());
        shopAddress.setAid(param.getAid());

        ShopAddress temp = new ShopAddress();
        temp.setIsDefault(false);
        shopAddressMapper.update(
                temp,
                Wrappers.<ShopAddress>lambdaQuery()
                        .eq(ShopAddress::getConsumerAid,param.getTokenConsumerAid())
        );
        shopAddress.setIsDefault(true);
        shopAddressMapper.updateById(shopAddress);
        return ResponseWrapper.markSuccess();
    }

    /**
     * 订单部分
     */
    /**
     * 1.查看当前用户所有订单
     * @return
     */
    public ResponseWrapper orderList(OrderListParam param){
        OrderListResult orderListResult = new OrderListResult();

        param.setSearchKey("%" + param.getSearchKey() + "%");
        Integer pageNum = (param.getPageNum() - 1) * param.getNum();
        param.setPageNum(pageNum);
        List<Map<String,Object>> orderList = personalCenterMapper.getOrderList(param);
        List<OrderList> orderLists = CommonTool.mapListToBeanList(orderList, OrderList.class);
        for (OrderList order : orderLists) {
            ShopOrderItem shopOrderItem = shopOrderItemMapper.selectList(
                    Wrappers.<ShopOrderItem>lambdaQuery()
                            .eq(ShopOrderItem::getOrderAid, order.getAid())
            ).get(0);
            order.setImg(shopOrderItem.getImage());
            order.setName(shopOrderItem.getName());
            order.setPrice(shopOrderItem.getPoints());
        }
        orderListResult.setOrderList(orderLists);
        orderListResult.setTotalNum(personalCenterMapper.getOrderListCount(param));

        //最后一步，返回结果
        return ResponseWrapper.markSuccess(orderListResult);
    }
    /**
     * 2.查看订单详情
     * @return
     */
    public ResponseWrapper orderInfo(OrderInfoParam param){
        OrderInfoResult orderInfoResult = new OrderInfoResult();

        //1.获取订单基本信息
        List<ShopOrder> shopOrders = shopOrderMapper.selectList(
                Wrappers.<ShopOrder>lambdaQuery()
                        .eq(ShopOrder::getAid, param.getAid())
        );
        if (!shopOrders.isEmpty()){
            ShopOrder shopOrder = shopOrders.get(0);
            BeanUtil.copyProperties(shopOrder,orderInfoResult);
            ShopOrderState shopOrderState = shopOrderStateMapper.selectOne(
                    Wrappers.<ShopOrderState>lambdaQuery().eq(ShopOrderState::getId, shopOrder.getStateId())
            );
            orderInfoResult.setStateName(shopOrderState.getName());
        }


        //2.获取订单项信息
        List<ShopOrderItem> shopOrderItemList = shopOrderItemMapper.selectList(
                Wrappers.<ShopOrderItem>lambdaQuery()
                        .eq(ShopOrderItem::getOrderAid, param.getAid())
        );

        List<OrderItemList> orderItemLists = new ArrayList<>();
        shopOrderItemList.forEach(item->{
            OrderItemList orderItemList = new OrderItemList();
            BeanUtil.copyProperties(item,orderItemList);
            orderItemLists.add(orderItemList);
        });

        orderInfoResult.setOrderItemList(orderItemLists);

        //最后一步，返回结果
        return ResponseWrapper.markSuccess(orderInfoResult);
    }
    /**
     * 3.获取订单状态列表
     * @return
     */
    public ResponseWrapper orderStateList(OrderStateListParam param){
        List<OrderStateListResult> orderStateListResults = new ArrayList<>();
        OrderStateListResult allOrderStateListResult = new OrderStateListResult();
        allOrderStateListResult.setId(-1);
        allOrderStateListResult.setName("全部订单");
        orderStateListResults.add(allOrderStateListResult);

        List<ShopOrderState> shopOrderStates = shopOrderStateMapper.selectList(null);
        for (ShopOrderState shopOrderState : shopOrderStates) {
            OrderStateListResult orderStateListResult = new OrderStateListResult();
            BeanUtil.copyProperties(shopOrderState,orderStateListResult);
            orderStateListResults.add(orderStateListResult);
        }
        //最后一步，返回结果
        return ResponseWrapper.markSuccess(orderStateListResults);
    }

    /**
     * 活动模块
     */
    /**
     * 1.查看用户参与的活动列表
     * @return
     */
    public ResponseWrapper activityList(ActivityListParam param){
        ActivityListResult activityListResult = new ActivityListResult();

        param.setSearchKey("%" + param.getSearchKey() + "%");
        Integer pageNum = (param.getPageNum() - 1) * param.getNum();
        param.setPageNum(pageNum);
        activityListResult.setTotalNum(personalCenterMapper.getActivityListCount(param));
        List<Map<String, Object>> activityList = personalCenterMapper.getActivityList(param);
        List<ActivityList> activityLists = CommonTool.mapListToBeanList(activityList, ActivityList.class);
        activityListResult.setActivityList(activityLists);

        //最后一步，返回结果
        return ResponseWrapper.markSuccess(activityListResult);
    }

    /**
     * 论坛模块
     */
    /**
     * 1.获取当前用户的全部帖子列表
     * @return
     */
    public ResponseWrapper postList(PostListParam param){
        PostListResult postListResult = new PostListResult();

        Page<ForumPost> pageInfo = new Page<>(param.getPageNum(),param.getNum(),true);
        Page<ForumPost> forumPostPage = forumPostMapper.selectPage(pageInfo,
                Wrappers.<ForumPost>lambdaQuery()
                        .eq(ForumPost::getConsumerAid,param.getTokenConsumerAid())
                        .eq(ForumPost::getIsDelete,false)
                        .like(ForumPost::getTitle, param.getSearchKey())
                        .orderByDesc(ForumPost::getTimeCreate)
        );
        postListResult.setTotalNum((int) forumPostPage.getTotal());
        List<ForumPost> forumPosts = forumPostPage.getRecords();
        List<PostList> postList = new ArrayList<>();

        for (ForumPost forumPost : forumPosts) {
            PostList postListItem = new PostList();
            BeanUtil.copyProperties(forumPost,postListItem);
            postList.add(postListItem);
        }
        postListResult.setPostList(postList);
        //最后一步，返回结果
        return ResponseWrapper.markSuccess(postListResult);
    }
    /**
     * 2.删除帖子(不实现，使用用户前台-论坛中的接口)
     * @return
     */
    public ResponseWrapper delPost(DelPostParam param){


        //最后一步，返回结果
        return ResponseWrapper.markSuccess();
    }
    /**
     * 3.获取当前用户所有回复列表
     * @return
     */
    public ResponseWrapper replyList(ReplyListParam param){
        ReplyListResult replyListResult = new ReplyListResult();
        
        Integer pageNum = (param.getPageNum() - 1) * param.getNum();
        param.setPageNum(pageNum);

        List<Map<String,Object>> replyList = personalCenterMapper.getReplyList(param);
        replyListResult.setTotalNum(personalCenterMapper.getReplyListCount(param));

        List<ReplyList> replyLists = CommonTool.mapListToBeanList(replyList, ReplyList.class);

        replyListResult.setReplyList(replyLists);

        //最后一步，返回结果
        return ResponseWrapper.markSuccess(replyListResult);
    }

    /**
     * 捐赠模块
     */
    /**
     * 1.查看当前用户全部捐赠记录
     * @return
     */
    public ResponseWrapper donationList(DonationListParam param){
        DonationListResult donationListResult = new DonationListResult();

        //获取总数
        Integer totalNum = donationMapper.selectCount(
                Wrappers.<Donation>lambdaQuery()
                        .eq(Donation::getConsumerAid,param.getTokenConsumerAid())
                        .like(Donation::getNumber, param.getSearchKey())
                        .or()
                        .like(Donation::getName,param.getSearchKey())
        );
        donationListResult.setTotalNum(totalNum);
        //获取分页数据
        Page<Donation> pageInfo = new Page<>(param.getPageNum(), param.getNum(),false);
        List<Donation> donationList = donationMapper.selectPage(pageInfo,
                Wrappers.<Donation>lambdaQuery()
                        .eq(Donation::getConsumerAid,param.getTokenConsumerAid())
                        .like(Donation::getNumber, param.getSearchKey())
                        .or()
                        .like(Donation::getName,param.getSearchKey())
        ).getRecords();
        List<DonationList> donationLists = new ArrayList<>();
        for (Donation donation : donationList) {
            DonationList donationListItem = new DonationList();
            BeanUtil.copyProperties(donation,donationListItem);
            donationLists.add(donationListItem);
        }
        donationListResult.setDonationList(donationLists);

        //最后一步，返回结果
        return ResponseWrapper.markSuccess(donationListResult);
    }
}